package com.linln.wtp.controller.shops;


import com.linln.common.utils.*;
import com.linln.common.vo.JsonResult;
import com.linln.component.wtpshiro.annotation.PassToken;
import com.linln.component.wtpshiro.annotation.UserLoginToken;
import com.linln.modules.shopsService.domain.Shops;
import com.linln.modules.shopsService.service.ShopsService;
import com.linln.modules.wtpshop.service.ShopService;
import com.linln.wtp.validator.WxShopsUpdateValid;
import com.linln.wtp.validator.WxShopsValid;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.configurationprocessor.json.JSONArray;
import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.InvocationTargetException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/shops")
public class ShopsSettleInController {
    @Autowired
    private ShopsService shopsService;

    @Autowired
    @Qualifier("shopService")
    private ShopService shopService;
    @Value("${server.ip}")
    private String ip;


    /**
     * 保存图片
     *
     * @param type 图片类型 4种类型具体看 ShopEnum枚举类
     * @return图片相对路径
     */
    @UserLoginToken
    @PostMapping("ajaxSaveImg")
    public JsonResult ajaxSaveImg(int type, String img) {
        return shopsService.saveVerificationImgByBase64(img, type);
    }

/*    @PassToken
    @GetMapping("getAreaData")
    public JsonResult getAreaData(String parentId){
        if(Strings.isBlank(parentId)){
            JsonResult.error("获取位置错误");
        }
        return JsonResult.ok().put("data",shopsService.getAreaData(parentId,""));
    }*/

    /**
     * 入驻店铺保存
     *
     * @param wxShopsValid
     * @param shops
     * @param shopTypes
     * @return
     */
    @UserLoginToken
    @PostMapping("/saveShop")
    public JsonResult saveShop(@Validated WxShopsValid wxShopsValid, Shops shops, String[] shopTypes) {
        if (shopTypes == null && shopTypes.length < 1) {
            JsonResult.error("店铺类型错误").setCode(400);
        }
        StringBuilder shopType = new StringBuilder();
        for (int i = 0; i < shopTypes.length; ++i) {
            if (i == 0) {
                shopType.append(shopTypes[i]);
            } else {
                shopType.append("," + shopTypes[i]);
            }
        }
        shops.setAreaId(shopsService.getAddressbyAreaId(shops.getAddress()));
        shops.setShopType(shopType.toString());
        //逻辑删除
        shops.setDelFlag("0");
        //入驻后默认状态
        shops.setAuditMark("0");
        //店铺初始状态休息中
        shops.setOpeningStatus("1");
        //没有id就代表新建
        shops.setShopId(UUIDUtil.randomUUID32());
        //店铺初始评分
        shops.setScore(5D);
        //创建日期时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        Date now = new Date();
        String time = sdf.format(now);
        shops.setCreateDate(time);
        shops.setShopPicture(PathMappingUtil.formatMapping(wxShopsValid.getPhysicalstoreMapping()));
        //扩展字段
        Map<String, Object> map = new HashMap<>();
        map.put("shopTypeName", shopsService.getShopTypeName(shopTypes));
        map.put("businesslicenseMapping", PathMappingUtil.formatMapping(wxShopsValid.getBusinesslicenseMapping()));
        map.put("constructionworkshopMapping", PathMappingUtil.formatMapping(wxShopsValid.getConstructionworkshopMapping()));
        map.put("technicianconstructionMapping", PathMappingUtil.formatMapping(wxShopsValid.getTechnicianconstructionMapping()));
        JSONObject jsonObject = new JSONObject(map);
        shops.setProps(jsonObject.toString());
        shops.setShopCreateUserId(Long.valueOf(SessionUtil.getUserId()).toString());
        try {
            shopsService.save(shops, SessionUtil.getUserId(), null, false);
            List<Map<String,Object>> mapList = shopsService.getByUserShops(Long.valueOf(shops.getShopCreateUserId()));
            return JsonResult.ok().put("data", mapList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JsonResult.error("保存失败");
    }


    @PostMapping("/updateShopAddress")
    public JsonResult updateShopAddress(Shops shop) {
        try {
            if (shopService.updateShopAddress(shop, SessionUtil.getUserId())) {
                return JsonResult.ok("修改位置成功").put("address", shop.getAddress());
            }
            return JsonResult.error("修改位置失败");
        } catch (Exception e) {
            log.error(e.getMessage());
            return JsonResult.error("修改位置失败");
        }
    }

    @PassToken
    @GetMapping("/getShopType")
    public JsonResult getShopType() {
        List<Map<String, Object>> shopTypes = shopsService.getShopType();
        List<Map<String, Object>> dataJson = new ArrayList<>();
        for (Map shopType : shopTypes) {
            Map<String, Object> map = new HashMap<>();
            map.put("label", shopType.get("name"));
            map.put("value", shopType.get("value"));
            dataJson.add(map);
        }
        return JsonResult.ok().put("data", dataJson);
    }

    /**
     * 店铺详细页面
     */
//    @UserLoginToken
    @GetMapping("/detail/{id}")
    public JsonResult toDetail(@PathVariable("id") Shops shops, @RequestParam("lon") String lon, @RequestParam("lat") String lat) {
        try {
            if (shops.getScore() == null) {
                shops.setScore(5.0);
            }
            //店铺详情图片地址转换
            String html = shops.getShopDetails();
            if(Strings.isNotBlank(html)){
                shops.setShopDetails(html.replaceAll("shenzhou.dl-it.cn","api.shenzhou.dl-it.cn"));
            }
            Map<String, Object> map = ObjectUtil.ObjectToMap(shops);
            map.put("rateConut", 0);
            List<String> imgs = new ArrayList<>();
            String img1 = (String) map.get("shopPicture");
            String img2 = (String) map.get("constructionworkshopMapping");
            String img3 = (String) map.get("technicianconstructionMapping");
            if (Strings.isNotBlank(img1)) {
                imgs.add(PathMappingUtil.formatUrl(ip, img1));
            }
            if (Strings.isNotBlank(img2)) {
                imgs.add(PathMappingUtil.formatUrl(ip, img2));
            }
            if (Strings.isNotBlank(img3)) {
                imgs.add(PathMappingUtil.formatUrl(ip, img3));
            }
            map.put("imgs", imgs);
            map.put("shopType", shopService.selectShopServiceType(shops.getShopType().split(",")));
            if (shops.getLongitude() != null && shops.getLatitude() != null) {
                if (!Strings.isBlank(shops.getLongitude()) && !Strings.isBlank(shops.getLatitude())) {
                    map.put("distance", DistanceUtil.distance(Double.parseDouble(lon), Double.parseDouble(lat), Double.parseDouble(shops.getLongitude()), Double.parseDouble(shops.getLatitude())));
                } else {
                    map.put("distance", 0);
                }
            } else {
                map.put("distance", 0);
            }
            return JsonResult.ok().put("data", map);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.error("获取店铺信息失败，具体错误：" + e.getMessage());
        }
    }


    @PostMapping("shopUpdate")
    public JsonResult shopUpdate(@Validated WxShopsUpdateValid wxShopsValid, Shops shops, String[] shopTypes) throws JSONException, InvocationTargetException, IllegalAccessException {
        Shops oldShop = shopsService.getById(shops.getShopId());
        if (shopTypes == null && shopTypes.length < 1) {
            JsonResult.error("店铺类型错误").setCode(400);
        }
        StringBuilder shopType = new StringBuilder();
        for (int i = 0; i < shopTypes.length; ++i) {
            if (i == 0) {
                shopType.append(shopTypes[i]);
            } else {
                shopType.append("," + shopTypes[i]);
            }
        }
        //实体店名称
        shops.setShopName(shops.getShopName());
        //位置
        shops.setAreaId(shopsService.getAddressbyAreaId(shops.getAddress()));
        //服务类型
        shops.setShopType(shopType.toString());
        //店铺主图
        shops.setShopPicture(PathMappingUtil.formatMapping(wxShopsValid.getPhysicalstoreMapping()));
        shops.setAuditMark("0");
        shops.setCreateDate(DateUtil.formatDate(new Date()));
        //扩展字段
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("shopTypeName", shopsService.getShopTypeName(shopTypes));
        jsonObject.put("businesslicenseMapping", PathMappingUtil.formatMapping(wxShopsValid.getBusinesslicenseMapping()));
        jsonObject.put("constructionworkshopMapping", PathMappingUtil.formatMapping(wxShopsValid.getConstructionworkshopMapping()));
        jsonObject.put("technicianconstructionMapping", PathMappingUtil.formatMapping(wxShopsValid.getTechnicianconstructionMapping()));
        shops.setProps(jsonObject.toString());
        //经纬度
        shops.setShopCreateUserId(String.valueOf(SessionUtil.getUserId()));
        //ObjectUtil.ObjectToMap(shops)
        JSONObject jsonObject2 = new JSONObject(ObjectUtil.ObjectToMap(shops));
        jsonObject = new JSONObject(oldShop.getPropsJson());
        String byteList = Arrays.toString(jsonObject2.toString().getBytes(StandardCharsets.UTF_8));
        jsonObject.put("newShop",byteList);
        oldShop.setProps(jsonObject.toString());
        try {
            shopsService.save(oldShop, SessionUtil.getUserId(), null, true);
            return JsonResult.ok("修改成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JsonResult.error("修改失败");
    }
}
